<?php
/**
 * Created by PhpStorm.
 * User: 任旭明 <846723340@qq.com>
 * Date: 2018/10/25
 * Time: 14:26
 */

namespace app\index\controller;

use app\model\CutDownModel;
use app\model\UserModel;
use app\model\WeChatModel;
use think\Controller;
use think\Request;

class CutDown extends Controller
{
    static protected $id;

    static protected $suffix;

    static protected $url;

    public function _initialize()
    {
        if (session('Auth.Uid')) {
            self::$id = session('Auth.Uid');
            self::$suffix = substr(self::$id, -1, 1);
        }
    }

    /**
     * @var 通过链接邀请页面
     */
    public function index($cid, $uid)
    {
        if ((int)$cid && (int)$uid) {
            $check = (new CutDownModel(substr($uid, -1, 1), '', '', 'sy_product_info pi', 'pi.id = ct.cut_pid', '', 'ct'))->findOne("ct.cut_id = {$cid} and pi.wtcdtp = 1 and ct.cut_uid = {$uid}", 'ct.cut_id');
            if ($check) {
                $limit = (int)input('get.limit') ? (int)input('get.limit') : 0;
                $list = (new CutDownModel( substr($uid, -1, 1), 'id', $limit, 'sy_user u', 'u.id = ct.cut_cid', '', 'ct'))->selectAll("ct.cut_oid = {$cid} ", 'u.username, u.icon, ct.cprice');
                if (!$limit) {
                    $info = (new CutDownModel(substr($uid, -1, 1)))->getCut_User_Good("ct.cut_id = {$cid} and ct.cut_cid = {$uid} and ct.cut_oid = 0", "pi.name, pi.product_id, pi.price, pi.member_price, pi.color, pi.size,pi.url, u.username, u.icon, pi.hmkcbc");
                    $count = (new CutDownModel(substr($uid, -1, 1)))->countNum("cut_oid = {$cid}", 'cut_id');
                    $this->assign('list', $list);
                    $this->assign('count', $count . '/' . $info['hmkcbc']);
                    $this->assign('info', $info);
                    $this->assign('oid', $cid);
                    $this->assign('uid', $uid);
                    return $this->fetch();
                }
                return json_encode($list);

            }
            echo "<script>alert('该链接已过期');window.location.href='/';</script>";
            return;
        }
    }

    /**
     * @var 砍价
     */
    public function save($oid, $uid)
    {
        if (session('Auth.Uid')) {
            $obj = (new CutDownModel(substr($uid, -1, 1)));
            $cInfo = (new CutDownModel(substr($uid, -1, 1), '', '', 'sy_product_info pi', 'pi.id = ct.cut_pid', '', 'ct'))->findOne("ct.cut_id = {$oid} and pi.wtcdtp = 1 and ct.cut_uid = {$uid}", 'ct.cut_uid, ct.create_time, pi.hmkcbc, pi.floorprice, pi.price');
            $endTime = strtotime(date('Y-m-d', $cInfo['create_time'])) + 8 * 60 * 60 * 24 - 1;
            $cutId = $obj->getValue('cut_cid = ' . self::$id, 'cut_cid');
            $cutNum = $obj->countNum("cut_oid = {$oid}", 'cut_cid');
            if (!$cInfo || $endTime - time() < 0) {
                $info = '该链接已经过期!';
            } elseif ($cInfo['cut_uid'] == self::$id) {
                $info = '不能给自己砍价哦!';
            } elseif ($cutId) {
                $info = '你已经砍过价了哦!';
            } elseif ($cutNum >= $cInfo['hmkcbc']) {
                $info = '已经达到最高砍价人数!';
            } else {
                $arr['cut_cid'] = self::$id;
                $arr['cprice'] = self::_cutPrice($cutNum, $cInfo['hmkcbc'], $cInfo['floorprice'], $cInfo['price']);
                $arr['create_time'] = time();
                $result = $obj->insertOne($arr);
                if ($result) {
                    $info = '砍价成功!';
                } else {
                    $info = '砍价失败!';
                }
            }
            $url = getUrl($_SERVER['HTTP_REFERER']);
            echo "<script>alert('" . $info . "');window.location.href='" . $url . "';</script>";
        } else {
            $url = empty($_SERVER['HTTP_REFERER']) ? '/' : $_SERVER['HTTP_REFERER'];
            $this->activity_login(getUrl($url));
        }
    }



    /**
     * @var 登录活动
     */
    public function activity_login($url = '')
    {
        $userInfo = (new WeChatModel())->getUserInfo($url);
        $result = (new UserModel())->findOne("openid = '{$userInfo['openid']}'", 'id, username');
        if ($result) {
            $this->_save($result['id'], $result['username'], $userInfo['url']);
        }
        $this->redirect('/activity_create?openid='.$userInfo['openid'].'&headimgurl='.$userInfo['headimgurl'].'&url='.$userInfo['url']);
    }

    /**
     * @var 保持回话
     */
    private function _save($id, $name, $url)
    {
        session('Auth.Uid', $id);
        session('Auth.Username', $name);
        $this->redirect($url);
    }

    /**
     * @var 活动注册 成功返回跳转页面
     */
    public function activity_create($data = '', $url = '')
    {
        $request = Request::instance();
        if ($request->isPost()) {
            $url = input('post.url') ? input('post.url') : '/';
            $arr['icon'] = input('post.icon') ? input('post.icon') : '';
            $arr['mobile'] = input('post.mobile') ? input('post.mobile') : '';
            $arr['openid'] = input('post.openid') ? input('post.openid') : '';
            $arr['username'] = input('post.surename') ? input('post.surename') : '';
            $arr['username'] = input('post.username') ? input('post.username') : '';
            if ($arr['mobile'] && $arr['username'] && $arr['username']) {
                $result = (new UserModel())->insertOne($arr);
                if ($result) {
                    self::_save($result, $arr['username'], $url);
                }
            }
            $result['code'] = 501;
            $result['info'] = '注册失败';
            return json_encode($result);
        }

//        var_dump($_GET);die;
        $this->assign('why', 0);
        $this->assign('openid', $_GET['openid']);
        $this->assign('icon', $_GET['headimgurl']);
        $this->assign('url', $_GET['url']);
        return $this->fetch();
    }

    static private function _getUrl($url)
    {
        $pat = '/(http:\/\/[^\/]+\/)/';
        $url = preg_replace($pat, '', $url);
        return '/' . $url;
    }

    /**
     * @var 砍价活动计算
     */
    static private function _cutPrice($count, $cutCount, $lowPrice, $price)
    {
        if ($cutCount - $count == 1) {
            $cutPrice = $price * 100 - $lowPrice * 100;
        } else {
            $avg = ($price * 100 - $lowPrice * 100) / $cutCount;
            $rand = rand((0 - $avg + 100), $avg * 2);
            $cutPrice = $avg + $rand;
        }
        return $cutPrice / 100;
    }
}
